<?php


namespace app\msgapi\service;

use app\utils\{Date, Http, Mail};
use PHPMailer\PHPMailer\PHPMailer;
use app\msgapi\model\{AdminUser,
    Cust,
    Department,
    GroupChat,
    HuihuaGroup,
    Senlog,
    Sensitive,
    SystemHeartbeat,
    User,
    System};
use think\facade\{Cache, Log};

class HuihuaSensitiveService extends BaseService
{
    public function __construct(Sensitive $sensitiveModel)
    {
        parent::__construct();
        $this->model = $sensitiveModel;
    }

    /**订阅列表
     * @param $data
     * @return array|\think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function getLists($data,$admin_groupid,$adminid){

        $adminlst = HsadminService::getAdminAccount($admin_groupid,$adminid,true); //获取可见管理员账号
        if($data['receive_user'] && !in_array($data['receive_user'],$adminlst)) return error_json('暂无此账号权限');
        $where[] = ['receive_user','=',$data['receive_user']?:$adminid];
        $limit = $data['limit'] ?: config('page.defaule_limit');
        $data['keyword']&&$where[] = ['attr','like',"%{$data['keyword']}%"];
        $data['type'] &&$where[] = ['type','=',$data['type']];
        $list = $this->model->where($where)->paginate($limit)->each(function ($item){
            $item['sender'] = User::where('userid','in',$item['userlist'])->column('name');
            return $item;
        })->toArray();
        return success_json('成功',$list);
    }


    /**新增保存\更新保存
     * @param $data
     * @return \think\response\Json
     */
    public function _save($data,$admin_groupid,$adminid)
    {
        $adminlst = HsadminService::getAdminAccount($admin_groupid,$adminid,true); //获取可见管理员账号
        if($data['receive_user'] && !in_array($data['receive_user'],$adminlst)) return error_json('暂无此账号权限');

        $data['attr'] = str_replace('：', ':', $data['attr']);
        $data['attr'] = str_replace('，', ',', $data['attr']);
        $rules = explode(':', $data['attr']);
        $data['receive_user'] = $data['receive_user'] ?? $adminid;
        if ($data['type'] == 'text' || $data['type'] == 'file' || $data['type'] == 'voip_doc_share') {
            if (count($rules) < 2) {
                return error_json('监管规则配置错误，请检查');
            }
            $data['rule'] = trim($rules[0]);
            if ($data['type'] == 'text') {
                if ($data['rule'] != 'content') {
                    return error_json('文本消息监管规则请以content:开头');
                }
            } else if ($data['type'] == 'file' || $data['type'] == 'voip_doc_share') {
                if ($data['rule'] != 'filename' && $data['rule'] != 'fileext') {
                    return error_json('文件/语音分享消息监管规则请以filename:或fileext:开头');
                }
            }
            $data['attr'] = trim($rules[1]);
        }
        try {
            $data['id'] ? $this->model->update($data,['id'=>$data['id']]) : $this->model->create($data);
            return success_json('保存成功');
        } catch (\Exception $e) {
            return error_json( '保存失败，请重试');
        }
    }

    /**快捷状态调整
     * @param $data
     * @return \think\response\Json
     */
    public function setStatus($data,$admin_groupid,$adminid)
    {
        $adminlst = HsadminService::getAdminAccount($admin_groupid,$adminid,true); //获取可见管理员账号
        if($data['receive_user'] && !in_array($data['receive_user'],$adminlst)) return error_json('暂无此账号权限');

        $this->model->allowField(['state','sort'])->update($data,['id'=>$data['id']]);
        return success_json('更新成功');
    }

    /**预警统计列表
     * @param $data
     * @return \think\response\Json
     */
    public function getSubscribeList($data,$admin_groupid,$adminid)
    {
        $adminlst = HsadminService::getAdminAccount($admin_groupid,$adminid,true); //获取可见管理员账号
        if($data['receive_user'] && !in_array($data['receive_user'],$adminlst)) return error_json('暂无此账号权限');
        $m = new Senlog();
        $year = $data['year'] ?? date('Y'); $limit = $data['limit'] ?: config('page.defaule_limit');
        $where[] = ['msgtime','between',[$year.'-01-01 00:00:00',$year.'-12-31 23:59:59']];
        $where[] = ['receive_user','=',$data['receive_user']?:$adminid];
        $list = $m->field("WEEK(msgtime) as week,count(id) as count")
            ->where($where)
            ->group('WEEK(msgtime)')
            ->paginate($limit)->each(function ($item)use($year){
                $item['weektime'] = Date::getWeekDateRange($year,$item['week']);
                return $item;
            })->toArray();
        return success_json('成功',$list);
    }

    /**预警统计查看时间段内预警消息
     * @param $data
     * @return \think\response\Json
     */
    public function getSenList($data,$admin_groupid,$adminid)
    {
        $adminlst = HsadminService::getAdminAccount($admin_groupid,$adminid,true); //获取可见管理员账号
        if($data['receive_user'] && !in_array($data['receive_user'],$adminlst)) return error_json('暂无此账号权限');
        $time = $data['weektime'] ?? Date::getWeekDateRangeForDate(); $limit = $data['limit']?:config('page.defaule_limit');
        $time = [
            $time[0] . ' 00:00:00',
            $time[1] . ' 23:59:59'
        ];
        $where[] = ['log.msgtime','between',$time];
        $msgtype = $data['msgtype'];
        $msgtype && $where[] = ['log.msgtype','=',$msgtype];
        $data['receive_user'] && $where[] = ['log.receive_user','=',$data['receive_user']];
        $list = Senlog::field('log.*,
                        cust.name as c_name,cust.avatar as c_avatar,cust.corp_name as c_corp_name,cust.type as c_type,
                        user.name as u_name,user.avatar as u_avatar,
                        inuser.avatar as inuser_avatar,inuser.position as position,
                        group.name as g_name,group.type as g_type           
           ')
            ->alias('log')
            ->join('cust cust', 'cust.external_userid = log.touser', 'left')
            ->join('user user', 'user.userid = log.touser', 'left')
            ->join('user inuser', 'inuser.userid = log.fromid', 'left')
            ->join('group_chat group', 'group.chat_id = log.roomid', 'left')
            ->where($where)
            ->paginate($limit)->toArray();
        return success_json('成功',$list);
    }

    /**关键词检查
     * @param $msgData
     * @return false|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkSensitive($msgData)
    {
        //过滤adt_state和set_state字段同时为不提醒的订阅
        $senlist = $this->model
            ->where('type', $msgData['mstype'])
            ->where("FIND_IN_SET('{$msgData['fromid']}',`userlist`)")
            ->where('state', 1)
            ->where("`adt_state` <> '4' OR `set_state` <> '2'")
            ->select()->toArray();
        if (!$senlist) return false;

        //是文本消息
        if ($msgData['mstype'] == 'text') {
            foreach ($senlist as $val) {
                $pattern = "/" . implode("|", explode(',', $val['attr'])) . "/i"; //定义正则表达式
                if (preg_match_all($pattern, $msgData['content'], $matches)) {
                    if ($matches[0]) {
                        //匹配到数据
                        $data = [
                            'sensitives' => implode(',', $matches[0]),
                            'receive_user' => $val['receive_user'],
                            'content' => $msgData['content'],
                            'admin_template'=>$val['admin_template'],
                            'send_template'=>$val['send_template'],
                            'adt_state' => $val['adt_state'],
                            'set_state' => $val['set_state']
                        ];
                        continue;
                    }
                }
            }
        } elseif ($msgData['mstype'] == 'file') {
            $msgbody = json_decode(htmlspecialchars_decode($msgData['msgbody']), true);
//            $msgbody =json_decode($msgData['msgbody'],true);
            foreach ($senlist as $val) {
                $pattern = "/" . implode("|", explode(',', $val['attr'])) . "/i"; //定义正则表达式
                if (preg_match_all($pattern, $msgbody[$val['rule']], $matches)) {
                    if ($matches[0]) {
                        //匹配到数据
                        $data = [
                            'sensitives' => implode(',', $matches[0]),
                            'receive_user' => $val['receive_user'],
                            'filename' => $msgbody['filename'],
                            'admin_template'=>$val['admin_template'],
                            'send_template'=>$val['send_template'],
                            'adt_state' => $val['adt_state'],
                            'set_state' => $val['set_state']
                        ];
                        continue;
                    }
                }
            }
        } elseif ($msgData['mstype'] == 'voip_doc_share') {
            $msgbody = json_decode(htmlspecialchars_decode($msgData['msgbody']), true);
            $filename = $msgbody['filename'];
            $fileexpload = explode('.', $msgbody['filename']);
            $fileext = end($fileexpload);
            foreach ($senlist as $val) {
                $pattern = "/" . implode("|", explode(',', $val['attr'])) . "/i"; //定义正则表达式
                if ($val['rule'] == 'filename') {
                    if (preg_match_all($pattern, $filename, $matches)) {
                        if ($matches[0]) {
                            //匹配到数据
                            $data = [
                                'sensitives' => implode(',', $matches[0]),
                                'receive_user' => $val['receive_user'],
                                'filename' => $filename,
                                'admin_template'=>$val['admin_template'],
                                'send_template'=>$val['send_template'],
                                'adt_state' => $val['adt_state'],
                                'set_state' => $val['set_state']
                            ];
                            continue;
                        }
                    }
                }elseif ($val['rule']== 'fileext'){
                    if (preg_match_all($pattern, $fileext, $matches)) {
                        if ($matches[0]) {
                            //匹配到数据
                            $data = [
                                'sensitives' => implode(',', $matches[0]),
                                'receive_user' => $val['receive_user'],
                                'filename' => $filename,
                                'admin_template'=>$val['admin_template'],
                                'send_template'=>$val['send_template'],
                                'adt_state' => $val['adt_state'],
                                'set_state' => $val['set_state']
                            ];
                            continue;
                        }
                    }
                }
            }
//            $msgbody =json_decode($msgData['msgbody'],true);
        } else {
            $default_msgbody = HuihuaMsgService::defaultMsgbody();
            foreach ($senlist as $val) {
                $data = [
                    'sensitives' => $default_msgbody[$msgData['mstype']],
                    'receive_user' => $val['receive_user'],
                    'admin_template'=>$val['admin_template'],
                    'send_template'=>$val['send_template'],
                    'adt_state' => $val['adt_state'],
                    'set_state' => $val['set_state']
                ];
                continue;
            }
        }
        if($data){
            $username = User::where('userid',$msgData['fromid'])->value('name');
            $data['sender'] = $username ? : $msgData['fromid'];
            $data['fromid'] = $msgData['fromid'];
            $data['msgtime'] = $msgData['msgtime'];
            $data['msgid'] = $msgData['msgid'];
            $data['msgtype'] = $msgData['mstype'];
            if($msgData['roomid']){
                $data['is_crowd'] =1;
                $data['roomid'] = $msgData['roomid'];
            }else{
                $data['touser'] = explode(',',$msgData['tolist'])[0];
            }
            $data['c_id'] = $msgData['c_id'];
            $data['group_id'] = $msgData['hs_group_id'];
            $info = Senlog::where('msgid',$msgData['msgid'])->findOrEmpty()->toArray();
            if(!$info) {
                Senlog::create($data);
            }
        }
    }

    /**订阅消息类型
     * @return string[]
     */
    public static function msgtype()
    {
        //订阅消息类型
        $msgtype = [
            'text'=>'文本消息',
            'file'=>'文件消息',
            'video'=>'视频消息',
            'voice'=>'语音条',
            'meeting_voice_call'=>'语音/视频聊天',
            'voip_doc_share'=>'语音分享文件',
        ];
        return $msgtype;
    }


    /**
     * 发送订阅消息,每分钟一次
     */
    public static function sendSensitive()
    {
        try {
            $list = Senlog::alias('senlog')
                ->join('admin_user ad_user','senlog.receive_user = ad_user.id')
                ->field('senlog.*,ad_user.userid,ad_user.email')
                ->where('send_state', 0)->select()->toArray();
            $msgtype = self::msgtype();
            foreach ($list as $v) {
                if ($v['admin_template']) { //发送订阅给管理员
                    $template = str_replace('{$sensitives}', $v['sensitives'], $v['admin_template']);
                    $template = str_replace('{$filename}', $v['filename'], $template);
                    $template = str_replace('{$msgtype}', $msgtype[$v['msgtype']], $template);
                    $template = str_replace('{$content}', $v['content'], $template);
                    $template = str_replace('{$sender}', $v['sender'], $template);
                    $template = str_replace('{$msgtime}', $v['msgtime'], $template);
                    if($v['userid']){
                        if(($v['adt_state'] == 1) || ($v['adt_state'] == 3)){
                            //1仅企业微信 3邮箱+企微
                            $weworkCorpSelf = new WeworkCorpSelfService();
                            Log::write('发送(监管管理员)敏感词订阅消息','info');
                            Log::write($weworkCorpSelf->sendTempMessage([$v['userid']],'markdown',$template),'info');
                        }
                        if(($v['adt_state'] == 2) || ($v['adt_state'] == 3)){
                            //2仅邮箱 3邮箱+企微
                            if($v['email']){
                                $PHPMailer = new PHPMailer();
                                $mail = new Mail($PHPMailer);
                                Log::write('发送(监管管理员)敏感词订阅邮件','info');
                                Log::write($mail->send( '订阅消息通知', '<p>'.$template.'</p>', $v['email']),'info');
                            }
                        }

                    }
                }
                if ($v['send_template']) { //发送订阅给消息发送人
                    $send_template = str_replace('{$sensitives}', $v['sensitives'], $v['send_template']);
                    $send_template = str_replace('{$filename}', $v['filename'], $send_template);
                    $send_template = str_replace('{$msgtype}', $msgtype[$v['msgtype']], $send_template);
                    $send_template = str_replace('{$content}', $v['content'], $send_template);
                    $send_template = str_replace('{$sender}', $v['sender'], $send_template);
                    $send_template = str_replace('{$msgtime}', $v['msgtime'], $send_template);
                    if($v['set_state'] == 1){ //1企业微信提醒 2不提醒
                        $weworkCorpSelf = new WeworkCorpSelfService();
                        Log::write('发送(消息发送人)敏感词订阅消息','info');
                        Log::write($weworkCorpSelf->sendTempMessage([$v['fromid']], 'markdown', $send_template),'info');
                    }

                }
                Senlog::where('id',$v['id'])->update(['send_state'=>1]);
            }
            return true;
        }catch (\Exception $e){
            Cache::set('is_sensitive',false,3600);
            Log::write('订阅消息发送失败,'.$e->getMessage().'line:'.$e->getLine(),'error');
        }
    }

    /**
     * 发送系统预警企微消息(每10分钟检查一次)
     */
    public static function sendSystemAbnormalSensitive()
    {
        $abnormal_notice_config = System::getSys('abnormal_notice_config');
        if(round(((disk_free_space('.')/disk_total_space('.')) * 100),2) > 10){
            SystemHeartbeat::update(['state_other'=>1,'add_time_other'=>date('Y-m-d H:i:s')],['id'=>1]); //系统心跳用,其他异常
            return true; //剩余空间大于10%不提醒
        }
        try {
            $disk_emaining_capacity = round(((disk_free_space('.')/disk_total_space('.')) * 100),2).' % '.'('.round((disk_free_space(".")/(1024*1024*1024)),2).'GB' .')'; //硬盘剩余使用率和容量
            $datetime = date('Y-m-d H:i:s');
            $template = "会话存档系统预警，请及时关注。
                    **预警内容**
                    硬盘空间剩余：{$disk_emaining_capacity}
                    发送时间：{$datetime}";
            if(($abnormal_notice_config['type'] == 2) || ($abnormal_notice_config['type'] == 3)){
                //2仅企业微信 3邮箱+企微
                $weworkCorpSelf = new WeworkCorpSelfService();
                Log::write('发送会话存档系统预警订阅消息','info');
                Log::write($weworkCorpSelf->sendTempMessage([$abnormal_notice_config['userid']],'markdown',$template),'info');
            }
            if(($abnormal_notice_config['type'] == 1) || ($abnormal_notice_config['type'] == 3)){
                //1仅邮箱 3邮箱+企微
                $PHPMailer = new PHPMailer();
                $mail = new Mail($PHPMailer);
                Log::write('发送会话存档系统预警订阅邮件','info');
                Log::write($mail->send( '预警通知', '<p>'.$template.'</p>', $abnormal_notice_config['email']),'info');
            }
            SystemHeartbeat::update(['state_other'=>2,'errmsg_other'=>"硬盘空间剩余：{$disk_emaining_capacity}",'add_time_other'=>date('Y-m-d H:i:s')],['id'=>1]); //系统心跳用,其他异常
            Cache::set('is_abnormal_sensitive',true,(strtotime(date("Y-m-d 09:00:00",strtotime("+1 day")))-time())); //缓存一天后再次提醒,防止因时间差缓存每次都推后问题
            return true;
        }catch (\Exception $e){
            Cache::set('is_abnormal_sensitive',false,(strtotime(date("Y-m-d 09:00:00",strtotime("+1 day")))-time()));
            Log::write('会话存档系统预警消息发送失败,'.$e->getMessage().'line:'.$e->getLine(),'error');
        }
    }

    /**会话存档服务到期订阅提醒
     * @return bool|void
     * @throws \Throwable
     */
    public static function sendServiceRemainDays()
    {
        $corp_info = HscorpInfoService::getCorpInfo(env('wework.corpid'),true);
        //剩余30天\15天\小于7天大于0天时通知
        $remain_days = ceil(((strtotime($corp_info['corp_info']['end_date']) - time()) / 86400)); //剩余天数
        $abnormal_notice_config = System::getSys('abnormal_notice_config');
        if($remain_days == 30 || $remain_days == 15 || ($remain_days <= 7 && $remain_days >=0)) {
            try {
                $datetime = date('Y-m-d H:i:s');
                $template = "会话存档服务到期预警，请及时关注。
                        **预警内容**
                        服务到期剩余：{$remain_days}天
                        发送时间：{$datetime}";
                if(($abnormal_notice_config['type'] == 2) || ($abnormal_notice_config['type'] == 3)){
                    //2仅企业微信 3邮箱+企微
                    $weworkCorpSelf = new WeworkCorpSelfService();
                    Log::write('发送会话存档服务到期预警订阅消息','info');
                    Log::write($weworkCorpSelf->sendTempMessage([$abnormal_notice_config['userid']],'markdown',$template),'info');
                }
                if(($abnormal_notice_config['type'] == 1) || ($abnormal_notice_config['type'] == 3)){
                    //1仅邮箱 3邮箱+企微
                    $PHPMailer = new PHPMailer();
                    $mail = new Mail($PHPMailer);
                    Log::write('发送会话存档服务到期预警订阅邮件','info');
                    Log::write($mail->send( '会话存档服务到期预警通知', '<p>'.$template.'</p>', $abnormal_notice_config['email']),'info');
                }
                SystemHeartbeat::update(['state_other'=>2,'errmsg_other'=>"会话存档服务到期剩余：{$remain_days}天",'add_time_other'=>date('Y-m-d H:i:s')],['id'=>1]); //系统心跳用,其他异常
                //缓存一天后再次提醒
                Cache::set('is_remain_days',true,(strtotime(date("Y-m-d 09:00:00",strtotime("+1 day")))-time()));
                return true;
            }catch (\Exception $e){
                Cache::set('is_remain_days',false,(strtotime(date("Y-m-d 09:00:00",strtotime("+1 day")))-time()));
                Log::write('会话存档服务到期预警消息发送失败,'.$e->getMessage().'line:'.$e->getLine(),'error');
            }
        }else{
            SystemHeartbeat::update(['state_other'=>1,'add_time_other'=>date('Y-m-d H:i:s')],['id'=>1]); //系统心跳用,其他异常
        }
        return true;
    }

    /**删人提醒
     * @param array $db_user_cust
     * @param string $ChangeType
     * @return void
     * @throws \app\utils\UtilsException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function sendDeletionReminder(array $db_user_cust, string $ChangeType)
    {
        $delete_cust_config = System::getSys('delete_cust_config');
        switch ($delete_cust_config['remindCode']){
            case '1':
                //指定成员
                $send_user_list = $delete_cust_config['users'];
                $send_email_list = AdminUser::where([['userid','in',$delete_cust_config['users']],['state','=',1]])->column('email');
                break;
            case '2':
                //部门上级
                $data = self::getUsersAndEmail($db_user_cust,false);
                $send_user_list = $data['send_user_list'] ? array_values(array_unique($data['send_user_list'])) : [];
                $send_email_list = $data['send_email_list'] ? array_values(array_unique($data['send_email_list'])) : [];
                break;
            case '3':
                //主部门上级
                $data = self::getUsersAndEmail($db_user_cust,true);
                $send_user_list = $data['send_user_list'] ? array_values(array_unique($data['send_user_list'])) : [];
                $send_email_list = $data['send_email_list'] ? array_values(array_unique($data['send_email_list'])) : [];
                break;
            default:
                $send_user_list = [];
                $send_email_list = [];
                break;
        }

        $datetime = date('Y-m-d H:i:s');
        if($ChangeType == 'del_external_contact'){
            $template = "成员删除客户提醒，请及时关注
                >**提醒内容**
                >成员名称：{$db_user_cust['user_name']}
                >客户名称：{$db_user_cust['cust_name']}
                >成员客户备注：{$db_user_cust['remark']}
                >删除类型：成员删除客户
                >删除时间：$datetime";
        }elseif ($ChangeType == 'del_follow_user'){
            $template = "客户删除成员提醒，请及时关注
                >**提醒内容**
                >成员名称：{$db_user_cust['user_name']}
                >客户名称：{$db_user_cust['cust_name']}
                >成员客户备注：{$db_user_cust['remark']}
                >删除类型：被客户删除
                >删除时间：$datetime";
        }
        if((($delete_cust_config['type'] == 2) || ($delete_cust_config['type'] == 3) && !empty($send_user_list))){
            //[2]仅企业微信 [3]邮箱+企微 4不提醒
            $weworkCorpSelf = new WeworkCorpSelfService();
            Log::write('发送成员删除客户提醒消息','info');
            $res = $weworkCorpSelf->sendTempMessage($send_user_list,'markdown',$template,0);
//            Log::write($res,'info');
        }
        if((($delete_cust_config['type'] == 1) || ($delete_cust_config['type'] == 3) && !empty($send_email_list))){
            //[1]仅邮箱 [3]邮箱+企微 4不提醒
            $PHPMailer = new PHPMailer(); $mail = new Mail($PHPMailer);
            Log::write('发送成员删除客户提醒邮件','info');
            $res = $mail->send( '删人提醒', '<p>'.$template.'</p>', $send_email_list);
//            Log::write($res,'info');
        }
    }

    /**返回部门上级或主部门上级的成员列表及管理员账号邮箱
     * @param array $db_user_cust
     * @param bool $is_main
     * @return array
     */
    private static function getUsersAndEmail(array $db_user_cust,bool $is_main)
    {
        $department_lst = $db_user_cust['department_list']; //部门列表
        $main_department = $db_user_cust['main_department']; //主部门
        //查询部门列表负责人
        if($is_main){
            $leaders = Department::where('id','=',$main_department)->value('department_leader'); //主部门负责人
        }else{
            $leaders = Department::where('id','in',$department_lst)->column('department_leader'); //部门负责人
            if($leaders) $leaders = implode(',',$leaders);
        }
        $leader_emails = AdminUser::where([['userid','in',$leaders],['state','=',1]])->column('email');
        $data['send_user_list'] = [$leaders];
        $data['send_email_list'] = $leader_emails;
        return $data;
    }

    /**发送系统心跳(每10分钟发送一次)
     * @return \think\response\Json
     * @throws \Throwable
     * @throws \app\utils\UtilsException
     */
    public static function sendSystemHeartbeat()
    {
        $data = [];
        $corpInfo = HscorpInfoService::getCorpInfo(env('wework.corpid'),true); //获取企业密钥信息
        $data['params']['code'] = $corpInfo['corp_info']['corpid'];
        $data['params']['name'] = $corpInfo['corp_info']['corp_full_name'];
//        $disk_remaining_capacity = round(((disk_free_space(env('filedir.system_dir'))/disk_total_space(env('filedir.system_dir'))) * 100),2).' % '; //硬盘剩余使用率
        $disk_used = round((((disk_total_space(env('filedir.system_dir')) - disk_free_space(env('filedir.system_dir')))/disk_total_space(env('filedir.system_dir'))) * 100),2).' % '; //硬盘使用率

        $data['sysInfo']['diskPersent'] = $disk_used;
        $data['sysInfo']['diskUse'] = round(((disk_total_space(env('filedir.system_dir')) - disk_free_space(env('filedir.system_dir')))/(1024*1024*1024)),2).'GB';
        $data['sysInfo']['diskRemain'] = round((disk_free_space(env('filedir.system_dir'))/(1024*1024*1024)),2).'GB';
        $system_heartbeat = SystemHeartbeat::where('id','=',1)->findOrEmpty()->toArray();
        $data['data']['state'] = $system_heartbeat['state']; //存档系统异常代码:1[系统正常],2[拉取异常],3[存储异常]
        $data['data']['errmsg'] = $system_heartbeat['errmsg'];//存档系统异常信息
        $data['data']['add_time'] = $system_heartbeat['add_time'];//存档系统异常捕获时间
        $data['data']['state_other'] = $system_heartbeat['state_other'];//其他异常代码 1[正常],2[异常]
        $data['data']['errmsg_other'] = $system_heartbeat['errmsg_other'];//其他异常信息
        $data['data']['add_time_other'] = $system_heartbeat['add_time_other'];//其他异常捕获时间
        Log::write(
            "\n" .'===================系统运行状态==================='."\n" .
            '硬盘使用率:'.$disk_used."\n" .
            '硬盘已用容量:'.$data['sysInfo']['diskUse']."\n" .
            '硬盘剩余容量:'.$data['sysInfo']['diskRemain']."\n" .
            '系统状态代码:'.$data['data']['state']."\n" .
            '系统运行信息:'.($data['data']['errmsg']?:'无')."\n" .
//            '系统错误信息捕捉时间:'.$data['data']['add_time']."\n" .
            '状态代码含义:1[系统正常],2[拉取异常],3[存储异常]'."\n".
            '[错误代码超过一定时长未能自动恢复则为系统运行异常]'."\n".
            '=================================================='."\n",
            'info');
        $http = new Http(['base_uri' => "http://81.68.157.8/"]);
        return success_json('成功',$http->request('POST','api/monitor',$data));
    }

    /**长时间不回复提醒*/
    public static function sendLongTimeNoReplyReminder()
    {
        //满足条件:(成员最后回复时间戳<客户最后发送时间戳) && ((当前时间戳-客户最后发送时间戳) > 指定时长) && (消息最后更新时间戳 > 超时提醒时间戳) && 非内部聊天
        //或满足条件:(成员最后回复时间戳<客户最后发送时间戳) && ((当前时间戳-指定时长) > 客户最后发送时间戳) && (消息最后更新时间戳 > 超时提醒时间戳) && 非内部聊天
        $longtime_noreply_config = System::getSys('longtime_noreply_config'); $datetime = date('Y-m-d H:i:s');
        $time = time(); $admin_set_time = bcmul($longtime_noreply_config['time'],60); //后台设置时长
        $sub_time = bcsub($time,$admin_set_time); //当前时间减去指定时长
        $where = []; $where[] = ["is_com","=",0];
        $whereOr = "((`cust_last_send_time` > `user_last_send_time`) OR (`user_last_send_time` < `cust_last_send_time`))";
        $where[] = ["cust_last_send_time","<",$sub_time];
        $whereOr = $whereOr . " AND ((`msg_last_up_time` > `last_noreply_remind_time`) OR (`last_noreply_remind_time` < `msg_last_up_time`))";
        if($longtime_noreply_config['sessionType'] == 1) $where[] = ['is_crowd','=',0]; //会话类型 sessionType 1单聊 2群聊 3全部
        if($longtime_noreply_config['sessionType'] == 2) $where[] = ['is_crowd','=',1];
        $huihuagrouplst = HuihuaGroup::where($where)->where($whereOr)->select()->toArray(); //所有满足条件的会话组

        $chatid_lst = array_column($huihuagrouplst,'chatid'); //会话组
        $chatid_lst_arr = [];
        $group_user_lst = array_column($huihuagrouplst,'userlist'); //成员及客户
        $all_users_and_groups = [];
        if($chatid_lst && (($longtime_noreply_config['sessionType'] == 1) || ($longtime_noreply_config['sessionType'] == 3))){

            foreach ($chatid_lst as $v)
            {
                $tmpv = explode('##',$v);
                $all_users_and_groups = [...$all_users_and_groups,...$tmpv];
                $chatid_lst_arr[] = $tmpv;
            }

            $all_users_and_groups = array_values(array_unique($all_users_and_groups));
        }
        if($group_user_lst && (($longtime_noreply_config['sessionType'] == 2) || ($longtime_noreply_config['sessionType'] == 3)))
        {
            foreach ($group_user_lst as $gv)
            {
                $all_users_and_groups = [...$all_users_and_groups,...$gv];
            }
            $all_users_and_groups = array_values(array_unique($all_users_and_groups));
        }

        //去除不是成员和不是被监管成员的信息(但只能支持被监管成员,不支持历史被监管成员)
        $users_lst = User::field("id,userid,name,department_list,main_department")->where([['userid','in',$all_users_and_groups],['ispermit','=',1]])->select()->toArray();
        if(empty($users_lst)){
            Log::write('暂无成员长时间未回复消息','info');
            return true;
        }

        $users = array_column($users_lst,'userid');
        $users_names = array_column($users_lst,'name','userid');
        $externaluserlist = Cust::where([['external_userid','in',$all_users_and_groups]])->column('name','external_userid');
        $group_namelist = GroupChat::where([['chat_id','in',$chatid_lst]])->column('name', 'chat_id');
        $group_userlist = GroupChat::where([['chat_id','in',$chatid_lst]])->column('userid_list','chat_id');

        //单聊发消息
        foreach ($chatid_lst_arr as $clv){
            $externalname = ''; $cv_userid = '';
            foreach ($clv as $cv){
                if(isset($externaluserlist[$cv])){
                    $externalname = $externaluserlist[$cv]; //客户名称
                }else{
                    if(in_array($cv , $users)) $cv_userid = $cv; //成员userid
                }
            }

            if($externalname && $cv_userid){
                if($longtime_noreply_config['isRemind'] == 1) self::sendIspermit($longtime_noreply_config['time'],$datetime,'客户单聊',$externalname,[$cv_userid]);
                self::sendAdminUser($users_names[$cv_userid],$datetime,'客户',$externalname,$longtime_noreply_config);
            }
        }


        $group_user_arr = [];
        $group_arr = [];
        //群聊发消息
        foreach ($chatid_lst as $glv)
        {
            foreach ($users as $userid){
                $groupname = ''; $cv_userid = '';
                if($glv && isset($group_userlist[$glv])){
                    $userids_arr = explode(',',$group_userlist[$glv]);
                    if(in_array($userid,$userids_arr)) $cv_userid = $userid;
                    $groupname = $group_namelist[$glv];
                }

                if($groupname && $cv_userid){

                    if(!in_array($groupname,$group_arr)) array_push($group_arr,$groupname);

                    $k = array_search($groupname,$group_arr);
                    if(!isset($group_user_arr[$k])){
                        $group_user_arr[$k] = ['gname'=>$groupname,'userids'=>[$cv_userid]];
                    }else{
                        array_push($group_user_arr[$k]['userids'],$cv_userid);
                    }
                }
            }
        }
        if($group_user_arr){
            foreach ($group_user_arr as $value)
            {
                if($longtime_noreply_config['isRemind'] == 1) self::sendIspermit($longtime_noreply_config['time'],$datetime,'外部群组',$value['gname'],$value['userids']);
                if($value['userids']){
                    $tmp = [];
                    foreach ($value['userids'] as $userid){
                        $tmp[] = $users_names[$userid];
                    }
                    self::sendAdminUser(implode('、',$tmp),$datetime,'群聊',$value['gname'],$longtime_noreply_config);
                }

            }
        }

        //更新通知时间戳
        HuihuaGroup::where('chatid','in',$chatid_lst)->update(['last_noreply_remind_time'=>time()]);
        return true;
    }

    //通知被监管成员
    private function sendIspermit($longtime_noreply,$datetime,$typestr,$name,$userid)
    {
        $usertemplate = "长时间未回复提醒，请及时关注。
            >提醒内容：你有一{$typestr}'{$name}'发来的消息{$longtime_noreply}分钟内未回复，请及时关注。
            >备   注：如已回复请忽略本消息。
            >发送时间：$datetime";
        $weworkCorpSelf = new WeworkCorpSelfService();
        Log::write("发送企微被监管成员长时间未回复消息提醒({$typestr})",'info');
        $res = $weworkCorpSelf->sendTempMessage($userid,'markdown',$usertemplate,0);
        Log::write($res,'info');
    }

    //通知管理员
    private function sendAdminUser($username,$datetime,$typestr,$name,$longtime_noreply_config)
    {
        $send_user_list = $longtime_noreply_config['remindObjectUser']; $send_email_list = [];
        if($longtime_noreply_config['remindObjectUser']) $send_email_list = AdminUser::where([['userid','in',$longtime_noreply_config['remindObjectUser']],['state','=',1]])->column('email');
        //template内容不能超出2048字节,也就是大约1024个中文字,后期如群成员名称过多可做优化
        $template = "长时间未回复提醒，请及时关注。
                    >提醒内容：成员{$username}超过{$longtime_noreply_config['time']}分钟未回复{$typestr}'{$name}'的消息，请及时关注。
                    >备   注：如已关注请忽略本消息。
                    >发送时间：$datetime";
        $send_email_title = '成员企微长时间未回复消息提醒';
        $log_info = ['发送企微长时间未回复消息提醒','发送企微长时间未回复消息邮件提醒'];
        if((($longtime_noreply_config['remindType'] == 2) || ($longtime_noreply_config['remindType'] == 3) && !empty($send_user_list))){
            //[2]仅企业微信 [3]邮箱+企微 4不提醒
            $weworkCorpSelf = new WeworkCorpSelfService();
            Log::write($log_info[0],'info');
            $res = $weworkCorpSelf->sendTempMessage($send_user_list,'markdown',$template,0);
            Log::write($res,'info');
        }
        if((($longtime_noreply_config['remindType'] == 1) || ($longtime_noreply_config['remindType'] == 3) && !empty($send_email_list))){
            //[1]仅邮箱 [3]邮箱+企微 4不提醒
            $PHPMailer = new PHPMailer(); $mail = new Mail($PHPMailer);
            Log::write($log_info[1],'info');
            $res = $mail->send( $send_email_title, '<p>'.$template.'</p>', $send_email_list);
            Log::write($res,'info');
        }
    }



}